package cn.ronghuanet.org.service.impl;

import cn.ronghuanet.basic.service.impl.BaseServiceImpl;
import cn.ronghuanet.basic.util.PageList;
import cn.ronghuanet.org.domain.Department;
import cn.ronghuanet.org.mapper.DepartmentMapper;
import cn.ronghuanet.org.query.DepartmentQuery;
import cn.ronghuanet.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void add(Department department) {
        // 设置新增时间为当前系统时间
        department.setCreateTime(new Date());
        // 新增时可以让它给我返回自增长的主键
        departmentMapper.insert(department);
        // 经过观察,部门的path = 父部门的path+/+自己部门的ID
        String path = "";
        if(Objects.nonNull(department.getParent()) && Objects.nonNull(department.getParent().getId())){
            Department parent = departmentMapper.loadById(department.getParent().getId());
            path = parent.getPath();
        }
        // 最后要加上自己部门的ID
        path = path + "/"+ department.getId();
        department.setPath(path);
        departmentMapper.update(department);
    }

    @Transactional
    @Override
    public void update(Department department) {
        // 经过观察,部门的path = 父部门的path+/+自己部门的ID
        String path = "";
        if(Objects.nonNull(department.getParent()) && Objects.nonNull(department.getParent().getId())){
            Department parent = departmentMapper.loadById(department.getParent().getId());
            path = parent.getPath();
        }
        // 最后要加上自己部门的ID
        path = path + "/"+ department.getId();
        department.setPath(path);
        // 设置修改时间为当前系统时间
        department.setUpdateTime(new Date());
        departmentMapper.update(department);
    }

    @Override
    public List<Department> getTree() {
        return departmentMapper.loadTree();
    }
}
